import json
import time

from selenium.webdriver import ActionChains
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from dama import Dama

class Base():

    def __init__(self,driver:WebDriver):
        self.driver= driver

    def open_url(self,url):
        self.driver.get(url)

    def find_element(self,loc):
        #使用异常处理
        try:
            WebDriverWait(self.driver,20,0.5).until(EC.presence_of_element_located(loc))
            return self.driver.find_element(*loc)
        except Exception as e:
            print("报错信息:",e)
            print("未定位到元素的变量值:",loc)


    def click(self,loc):
        self.find_element(loc).click()

    def send_keys(self,loc,data):
        self.find_element(loc).send_keys(data)
    #获取文本属性值
    def get_text(self,loc):
       return self.find_element(loc).text

    #弹窗处理
    def alert_handle(self):
        alert= self.driver.switch_to.alert
        alert.accept()

    #iframe
    #滑动
    #下拉框架
    #切换新的页面
    #悬停
    # def move_to_hover(self,loc):
    #     ActionChains(self.driver).move_to_element(self.find_element(loc)).perform()
    def move_to_element(self,loc):
        ActionChains(self.driver).move_to_element(self.find_element(loc)).perform()
    #截屏的方法
    def screen(self,filename):
        t=time.strftime("%Y%m%d%H%M%S",time.localtime())
        self.driver.save_screenshot(t+filename)
    #dama
    def Dm(self,loc):
        self.find_element(loc).screenshot('./img/code.png')
        yam=open('./img/code.png','rb').read()
        dm = Dama('yjj030220 ', 'd0ur1r6m', '971195')
        return dm.PostPic(yam,1902)['pic_str']

    #封装getcookie
    def getcookie(self):
        #获取cookier
        cookier=self.driver.get_cookies()
        with open('./data/cookie.txt','w') as f:
            f.write(json.dumps(cookier))
        f.close()


    #cookier登录的方法
    def cookie_login(self):
        #清楚当前的cookie
        self.driver.delete_all_cookies()
        #读取存储的cookier
        with open('./data/cookie.txt','r') as f:
            #按照json的格式读取
            cookier=json.loads(f.read())
            #获取cookie
            for cookie in cookier:
                self.driver.add_cookie(cookie)
        f.close()
        self.driver.refresh()




